package fmi.chesstern.ui.gui;

import fmi.chesstern.controller.GameCommandExecutor;
import fmi.chesstern.controller.GameCommandParameters;
import fmi.chesstern.controller.GameCommandType;
import fmi.chesstern.game.BoardField;
import fmi.chesstern.game.Move;
import fmi.chesstern.pieces.ChessPiece;

public class GUIController {
	private GameCommandExecutor commandExecutor;
	private GUIBoardState state;
	
	public GUIController(GameCommandExecutor commandExecutor, GUIBoardState state) {
		this.commandExecutor = commandExecutor;
		this.state = state;
	}
	
	public void startNewGame() {
		commandExecutor.executeCommand(GameCommandType.NEW_GAME, null);
	}
	
	public void undo() {
		commandExecutor.executeCommand(GameCommandType.UNDO, null);
	}
	
	public void exit() {
		commandExecutor.executeCommand(GameCommandType.EXIT, null);
	}
	
	public void makeMove(Move move) {
		state.setSelectedField(null);
		
		GameCommandParameters parameters = new GameCommandParameters();
		parameters.setParameter("move", move);
		
		commandExecutor.executeCommand(GameCommandType.MOVE, parameters);
	}
	
	public void click(BoardField field) {
		ChessPiece piece = state.getGameState().getGameBoardState().getPieceAt(field);
		
		if (state.getSelectedField() != null && state.getSelectedField().equals(field)) {
			state.setSelectedField(null);
		} else if(state.getTargetFields().contains(field)) {
			makeMove(new Move(state.getSelectedField(), field));
		} else if (piece != null && piece.getColor() == state.getGameState().getGameBoardState().getCurrentPlayer()) {
			state.setSelectedField(field);
		}
	}
}
